# log flow server
# read log files and send it to client by network

import sys
import time
import logging
import json

from server import FileModifyReader, FlowServer


class FlowTask:
    def __init__(self, config):
        self.config = config


logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

config_file = sys.argv[1] if len(sys.argv) > 1 else 'config.json'
config = json.loads(open(config_file).read())
print(config)

buf = []
observer_list = []

for task in config.get("task_list"):
    print(task)
    file_modify_reader = FileModifyReader(task, buf)
    observer = file_modify_reader.run()
    observer_list.append(observer)

server = FlowServer(buf)

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt as e:
    print("")
    print('try stoping observer')
    for observer in observer_list:
        observer.stop()
        observer.join()
    print('observer stoped gracefully')

    print('try stoping server')
    server.stop()
    print('server stoped gracefully')

